/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/27 10:02
 */
package org.mechanic.fund.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.Session;
import org.mechanic.core.web.HttpStatusCode;
import org.mechanic.exception.BaseException;
import org.mechanic.exception.IllegalParameterException;
import org.mechanic.fund.domain.system.manager.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Controller 父类。所有 Controller 需继承该类
 *
 * @author mechanic
 * @version 0.0.1
 */
@RestController
public class BaseController {
    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    private int page = 0;
    private int size = 10;

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    protected PageRequest pageRequest(int page) {
        return pageRequest(page, size, null);
    }

    protected PageRequest pageRequest(int page, int size) {
        return pageRequest(page, size, null);
    }

    protected PageRequest pageRequest(int page, Sort sort) {
        return pageRequest(page, size, sort);
    }

    protected PageRequest pageRequest(int page, int size, Sort sort) {
        return new PageRequest(page, size, sort);
    }



    /**
     * 获取当前登录的用户信息
     */
    protected User currUser() {
        Session session = SecurityUtils.getSubject().getSession();
        if (session == null) {
            return null;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return null;
        }
        return user;
    }

    /**
     * 设置无返回数据成功响应代码
     */
    protected ResponseEntity<ModelMap> result() {
        return result(HttpStatusCode.OK);
    }

    /**
     * 设置带有返回数据的成功响应代码
     *
     * @param data 返回数据
     */
    protected ResponseEntity<ModelMap> result(Object data) {
        return result(HttpStatusCode.OK, data);
    }

    /**
     * 设置无返回数据的响应代码
     *
     * @param code 响应代码
     */
    protected ResponseEntity<ModelMap> result(HttpStatusCode code) {
        return result(code, null);
    }


    /**
     * 设置带有返回数据的响应代码
     *
     * @param code 响应代码
     * @param data 返回客户端的数据
     */
    protected ResponseEntity<ModelMap> result(HttpStatusCode code, Object data) {
        ModelMap map = new ModelMap();
        if (data != null) {
            map.put("data", data);
        }
        map.put("status", code.value());
        map.put("message", code.message());
        map.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(map);
    }

    /**
     * 异常处理
     */
    @ExceptionHandler(Exception.class)
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
      throws Exception {
        ModelMap modelMap = new ModelMap();
        if (ex instanceof BaseException) {
            ((BaseException) ex).handler(modelMap);
        } else if (ex instanceof IllegalArgumentException) {
            new IllegalParameterException(ex.getMessage()).handler(modelMap);
        } else if (ex instanceof UnauthorizedException) {
            result(HttpStatusCode.FORBIDDEN);
        } else {
            result(HttpStatusCode.INTERNAL_SERVER_ERROR);
        }
        request.setAttribute("msg", modelMap.get("msg"));
        response.setContentType("application/json;charset=UTF-8");
        byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
        response.getOutputStream().write(bytes);
    }
}
